package org.lzy.shop.view

import android.content.Context
import android.text.InputFilter
import android.text.Spanned
import android.util.AttributeSet
import com.google.android.material.textfield.TextInputEditText
import java.util.regex.Pattern

/**
 * EditText 添加限制Emoji表情
 */
class NoEmojiEditText : TextInputEditText {
    private var emoji: Pattern? = null
    private  var emojiFilters: Array<InputFilter?>?=null

    constructor(context: Context) : super(context) {
        setleng()
        init(context)
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        setleng()
        init(context)
    }

    private fun init(context: Context?) {
        emoji = Pattern.compile(
            "[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
            Pattern.UNICODE_CASE or Pattern.CASE_INSENSITIVE
        ) //emoji表情的正则
        //创建一个新的过滤规则
        val emojiFilter: InputFilter = object : InputFilter {
            override fun filter(
                source: CharSequence,
                start: Int,
                end: Int,
                dest: Spanned?,
                dstart: Int,
                dend: Int
            ): CharSequence? {
                val emojiMatcher = emoji!!.matcher(source) //对输入edittext的输入内容进行比对
                if (emojiMatcher.find()) {          //如果返回时true 进行Toast并返回空字符串 来替换原来的字符串  如果为false 直接返回null 返回null是直接不做处理用接收到的值进行展示
                    return ""
                }
                return null
            }
        }
        //将过滤规则加入过滤器中
        emojiFilters?.set(emojiFilters!!.size - 1, emojiFilter)
        filters = emojiFilters
    }

    //将Edittext原有的限制添加上去
    private fun setleng() {
        val filters = getFilters()
        emojiFilters = arrayOfNulls<InputFilter>(getFilters().size + 1)
        for (i in 0..<(emojiFilters?.size?.minus(1) ?: 0)) {
            emojiFilters?.set(i, filters[i])
        }
    }
}
